//
//  ViewController.m
//  ConuntStep
//
//  Created by dllo on 16/4/19.
//  Copyright © 2016年 C. All rights reserved.
//

#import "ViewController.h"
#import "Masonry.h"
#import "ArcView.h"
#import <CoreMotion/CoreMotion.h>


@interface ViewController ()<UIScrollViewDelegate>
{
    ArcView *view1;
    NSInteger v;

}
@property(nonatomic, strong) CMMotionManager *motionManager;
@property(nonatomic, strong) NSMutableArray *arrayData;/**< 用于写本地装步数和时间的字典 */
@property(nonatomic, strong) NSDictionary *dicData;/**< 用来装步数和时间 */


//@property(nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation ViewController
//
@synthesize dayView;
@synthesize monthView;
@synthesize yearView;

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建圆盘视图  并且赋值
    [self createCircleView];
    //以CoreMotion方式获取加速度计的参数(iOS5系统以后)
    [self accelerometerOfCoreMotionType];
//
    [self createScrollView];
    [self createSeg];
//折线图view
//dayView
    self.dayView = [[UIView alloc]initWithFrame:CGRectMake(8, 0, 355-16 , 180)];
    self.dayView.backgroundColor = [UIColor greenColor];
    [self.scrollView addSubview:self.dayView];
    
    array=[[NSMutableArray alloc]initWithObjects:@"1000",@"700",@"900",@"1200",@"1500",@"800",@"1000",@"2000",@"2000",@"3000",@"2345",@"3456",@"1234",@"567",@"4500",@"3500",@"2500",@"1212",@"777",@"2457",@"222",@"100",@"0",@"0", nil];
    dayView.layer.masksToBounds=YES;
    dayView.layer.cornerRadius=6.0;
    dayView.layer.borderWidth=1.0;
    dayView.layer.borderColor=[[UIColor whiteColor]CGColor];
    [self performSelector:@selector(dayVieww) withObject:nil afterDelay:.1];
//monthView
    self.monthView = [[UIView alloc]initWithFrame:CGRectMake(355+8, 0, 355 - 16, 180)];
    self.monthView.backgroundColor = [UIColor lightGrayColor];
    [self.scrollView addSubview:self.monthView];
    
    array=[[NSMutableArray alloc]initWithObjects:@"1500",@"800",@"2000",@"3000",@"2345",@"3456",@"1234",@"567",@"4500",@"3500",@"2500",@"1212",@"777",@"2457",@"222",@"100",@"0",@"0", nil];
    monthView.layer.masksToBounds=YES;
    monthView.layer.cornerRadius=6.0;
    monthView.layer.borderWidth=1.0;
    monthView.layer.borderColor=[[UIColor whiteColor]CGColor];
    [self performSelector:@selector(monthVieww) withObject:nil afterDelay:.1];
//yearView
    self.yearView = [[UIView alloc]initWithFrame:CGRectMake(355 * 2 + 8, 0, 355 - 16, 180)];
    self.yearView.backgroundColor = [UIColor lightGrayColor];
    [self.scrollView addSubview:self.yearView];
    
    array=[[NSMutableArray alloc]initWithObjects:@"1000",@"700",@"900",@"1200",@"1500",@"800",@"1000",@"2000",@"2000",@"3000",@"2345",@"3456",@"1234",@"567",@"4500",@"3500",@"2500",@"1212",@"777",@"2457",@"222",@"100",@"0",@"0", nil];
    yearView.layer.masksToBounds=YES;
    yearView.layer.cornerRadius=6.0;
    yearView.layer.borderWidth=1.0;
    yearView.layer.borderColor=[[UIColor whiteColor]CGColor];
    [self performSelector:@selector(yearVieww) withObject:nil afterDelay:.1];
    
}
-(void)createScrollView{
    //
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 360, 375-20, 180)];
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    self.scrollView.delegate = self;
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.scrollEnabled = YES;
    self.scrollView.directionalLockEnabled = YES;
    self.scrollView.contentSize = CGSizeMake(3 * 375, 180);
    self.scrollView.showsHorizontalScrollIndicator = YES;
    
    [self.view addSubview:self.scrollView];
//    _scrollView = self.scrollView;
    
   


    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat offset = scrollView.contentOffset.x;
    
    self.segment.selectedSegmentIndex = offset/self.view.frame.size.width;
}
-(void)createSeg{
    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:@[@"日",@"月",@"年"]];
    seg.frame = CGRectMake(10, 330, 375 - 20, 30);
    [self.view addSubview:seg];
    //选中分段下标
//    seg.selectedSegmentIndex = 0;
    seg.tintColor = [UIColor lightGrayColor];
    //添加显示事件(通过下标值得变化触发方法)
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];

}

//折线背景view
-(void)dayVieww{
    sView=[[LineView alloc]initWithFrame:CGRectMake(0, 0, self.dayView.frame.size.width, self.dayView.frame.size.height)];
    sView.backgroundColor=[UIColor lightGrayColor];
    sView.array=array;
    sView.number=@"5000";
    sView.count=@"24";
    [dayView  addSubview:sView];
    
    
}
-(void)monthVieww{
    sView=[[LineView alloc]initWithFrame:CGRectMake(0, 0, self.monthView.frame.size.width, self.monthView.frame.size.height)];
    sView.backgroundColor=[UIColor lightGrayColor];
    sView.array=array;
    sView.number=@"5000";
    sView.count=@"18";
    [monthView  addSubview:sView];
    
    
}
-(void)yearVieww{
    sView=[[LineView alloc]initWithFrame:CGRectMake(0, 0, self.yearView.frame.size.width, self.yearView.frame.size.height)];
    sView.backgroundColor=[UIColor lightGrayColor];
    sView.array=array;
    sView.number=@"5000";
    sView.count=@"10";
    [yearView  addSubview:sView];
    
    
}

#pragma mark - 分段控制器
-(void)segAction:(UISegmentedControl *)seg{

    if (seg.selectedSegmentIndex == 0) {
        self.scrollView.contentOffset = CGPointMake(0 , 0);

    }else if (seg.selectedSegmentIndex == 1){
        self.scrollView.contentOffset = CGPointMake(355 , 0);

    
    }else{
        self.scrollView.contentOffset = CGPointMake(355*2 , 0);

    }

    

    NSLog(@"%ld",seg.selectedSegmentIndex);
}


///创建圆盘视图  并且赋值
-(void)createCircleView
{
    view1  =[[ArcView alloc]initWithFrame:CGRectMake(0,0, kScreenWidth - 10 * 2,kScreenWidth - 30)];
    view1.backgroundColor = [UIColor whiteColor];
    //拼接写本地的路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *arrPath = [path stringByAppendingPathComponent:@"arr.plist"];
    //查看路径下是否存在plist文件
    //如果不存在就创建一个数组放到plist文件
    if(![[NSFileManager defaultManager] fileExistsAtPath:arrPath]){
        NSMutableArray *dictplist = [NSMutableArray array];
        [dictplist writeToFile:arrPath atomically:YES];
    }else{
        //如果存在,每次摇晃的时候都要从本地读取数据,取到数组的最后一个元素,并和最新的数据比较
        NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:arrPath];
        //当数组元素的个数是0的时候让圆盘显示也是 0
        if (arr.count==0) {
            view1.num = 0;
        }else{
            //当数组有元素的时候取到最后一个字典的数据
            NSMutableDictionary *currentDic = arr.lastObject;
            view1.num = [currentDic[@"stepCount"]integerValue];
        }
        NSLog(@"数组个数是------------%d",arr.count);
    }
    [self.view addSubview:view1];
}


//以CoreMotion方式获取加速度计的参数(iOS5系统以后)
-(void)accelerometerOfCoreMotionType{
    self.motionManager = [CMMotionManager new];
    //告诉系统更新频率为10HZ;
    self.motionManager.accelerometerUpdateInterval = 0.1;
    [self startShake];
}

//开始摇动
-(void)startShake{
     // 检查传感器到底在设备上是否可用
    if ([self.motionManager isAccelerometerAvailable]) {
        [self.motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc]init] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            if (error) {
                [self.motionManager stopAccelerometerUpdates];
            }else{
                //综合3各方向的加速度
               double accelerameter =sqrt( pow(accelerometerData.acceleration.x , 2 ) + pow(accelerometerData.acceleration.y , 2 ) + pow(accelerometerData.acceleration.z , 2) );
                //当综合加速度大于2.3时,就激发效果(此数值根据需求可以调整,数据越小,用户摇动的动作越小,越容易激发,反之加大难度,但容易误触发)
                if (accelerameter > 2.3f) {
                    //立即停止更新加速仪
                    [self.motionManager stopAccelerometerUpdates];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //拼接文件路径
                        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
                        NSString *arrPath = [path stringByAppendingPathComponent:@"arr.plist"];
                        //每次摇晃的时候都要从本地读取数据,取到数组的最后一个元素,并和最新的数据比较
                        NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:arrPath];
                            //当前日期
                        NSDate *now = [NSDate date];
                        //把当前的日期转化成字符串
                        NSString *timeStr = [NSString stringWithFormat:@"%@",now];
                        //本天日期字符串
                        NSString *dayStr = [timeStr substringToIndex:10];
                        //小时字符串
                        NSString *hourStr = [timeStr substringToIndex:13];
                        //这个方法用来判断当前摇晃的时候 产生的字典是不是已经包含在了数组内
                        BOOL isContain  =  [self whetherContainCurrentHour];
                        //当数组的个数是0的时候
                        if (arr.count==0) {
                            //圆盘的值为0
                           view1.num = 0;
                            //并创建一个字典把步数增加一   存到数组里去
                            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                            [dic setObject:hourStr forKey:@"time"];
                            [dic setObject:@"1" forKey:@"stepCount"];
                            [arr addObject:dic];
                            //把数组存到本地
                            [arr writeToFile:arrPath atomically:YES];
                        }else{
                            //当数组的个数不为0的时候 遍历数组
                            //如果已经包含了 说明今天的值已经获取到了
                            if (isContain == YES) {
                                for ( NSMutableDictionary *currentDic  in arr) {
                               //然后把今天的所有的值加一起
                                NSInteger stepCount = 0;
                                if ([currentDic[@"time"] hasPrefix:dayStr]) {
                                    stepCount  = [currentDic[@"stepCount"]integerValue] +stepCount;
                                }
                               // 然后显示到圆盘上
                                view1.num = stepCount+1;
                            }
                               //最新的字典肯定是最后添加的所以找到数组的最后一个元素
                                NSMutableDictionary *dic = arr.lastObject;
                                NSString *stepStr= [NSString stringWithFormat:@"%d",[dic[@"stepCount"]integerValue]+1];
                                [dic setObject: stepStr forKey:@"stepCount"];
                                [dic setObject:hourStr forKey:@"time"];
                                //把最后的字典移除
                                [arr removeObject:arr.lastObject];
                                //把新创建的字典赋值好以后添加到数组当中去
                                [arr addObject:dic];
                                [arr writeToFile:arrPath atomically:YES];
                            }else{
                                //如果没有获取到就创建一个新的字典
                                //存的时候我们只需要把日期截取到小时就可以
                                //stepCount 记录的是步数
                                //time 记录的是当前的时间精确到小时
                                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                                [dic setObject:hourStr forKey:@"time"];
                                [dic setObject:[NSString stringWithFormat:@"%d",v] forKey:@"stepCount"];
                                [arr addObject:dic];
                                [arr writeToFile:arrPath atomically:YES];
                            }
                        }
                        NSLog(@"摇晃后数组个数======%d",arr.count);
                        [self startShake];
                    });
                }
            }
        }];
    }
}

//用这个方法来判断数组里是否包含今天  如果包含就返回YES  如果不包含就返回NO
-(BOOL)whetherContainCurrentHour
{
    //路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //拼接路径
    NSString *arrPath = [path stringByAppendingPathComponent:@"arr.plist"];
    //每次摇晃的时候都要从本地读取数据,取到数组的最后一个元素,并和最新的数据比较
    NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:arrPath];
    //找出今天的日期
    NSDate *now = [NSDate date];
    //把日期转化成字符串
    NSString *str = [NSString stringWithFormat:@"%@",now];
    //因为字典里time里保存的值都是 精确到秒 我们判断的时候需要判断到小时   所以需要截取一下字符串
    NSString *dateStr = [str substringToIndex:13];
    //遍历数组 是否包含当前小时
    for (NSMutableDictionary *dic  in arr) {
        if ([dic[@"time"] hasPrefix:dateStr]) {
            return YES;
        }
    }
    return NO;
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
